<template>
	<view class="createRoom">
		<!-- #ifdef H5 -->
		<recording ref="recording" @success='recordingSuccess'></recording>
		<!-- #endif -->
		<!-- #ifdef APP -->
		<appRecording ref="appRecording" @success='recordingSuccess'></appRecording>
		<!-- #endif -->
		<view v-for="(item) in variables" :key="item.key">
				<customTitle>{{item.title}}</customTitle>
				<view class="item">
					<view class="itemBody">
						<textarea v-model="item.value" class="textArea" maxlength='500' :placeholder="`输入描述语，例如:${item.placeholder},最多500字`"></textarea>
					</view>
				</view>
				<view class="audioBtn" @longpress="startRecord(item)" @touchend="stopRecord" v-if="item.voice == 1">
					<image src="/static/maik.png" mode="" class="icon"></image>长按说话
				</view>
		</view>
		<button class="create" @click="createAI">AI生成</button>
		
		<view class="item c">
			<view class="title">AI生成</view>
			<view class="itemBody" :class="{placeholder: !result}">
				<view class="stop" v-if="loading" @click="aiStop">停止</view>
				{{result || '请输入输入关键词或描述语,生成文案!'}}
				<view class="textCount" v-if="result.length">{{result.length}}字</view>
				<view class="handle" v-if="result">
					<view class="plain btn" @click="copy">
						<image class="icon" src="../../static/copy.png" mode=""></image>
						复制
					</view>
					<view class="btn dark" @click="deleteResult">
						<image class="delete" src="../../static/delete.png" mode=""></image>
						删除
					</view>
				</view>
			</view>
		</view>
		<openVip></openVip>
		<safeBottom></safeBottom>
	</view>
</template>

<script>
	import ioSocket from '@/utils/ioSocket.js'
	export default {
		data() {
			return {
				text: '',
				result: '',
				data: '',//选中的模板信息
				variables: [],
				talkingItem: '',//录音属于谁
				loading: false,
				socketDistance: ''
			};
		},
		onLoad({name,variables,}) {
			this.data = uni.getStorageSync('createItem')
			// uni.removeStorageSync('createItem')
			uni.setNavigationBarTitle({
				title: name
			})
			this.setVariables()
		},
		methods: {
			// 生成AI文案
			async createAI() {
				if(this.loading) return;
				if(this.variables.some(item => !item.value)) {
					uni.showToast({
						title: '请填写文案要求！',
						icon:'none'
					})
					return
				}
				let variables = {}
				this.variables.forEach(item => {
					variables[item.key] = item.value
				})
				const have = await this.$checkAuth()
				if(!have) return;
				this.loading = true;
				// #ifdef APP
				this.openSocket({
						spellId: this.data.id,
						variables
					})
				// #endif
				// #ifdef H5
				this.openStream({
						spellId: this.data.id,
						variables
					})
				// #endif
			},
			// 停止ai输出
			aiStop() {
				// #ifdef APP
				this.socketDistance.close({code:1000})
				// #endif
				// #ifdef H5
				this.socketDistance = 'stop'
				this.loading = false;
				// #endif
			},
			openStream(data) {
				uni.showLoading({
					title:'生成中...',
					icon:'none'
				})
				this.loading = true;
				this.result = ''
				this.$stream({
					url:'/api/v1/miletus/word/ai/chat/base/stream',
					data,
					success: res => {
						if(this.loading) {
							uni.hideLoading()
						}
						if(this.socketDistance) return;
						this.result += `${this.isEnOrNum(res) ? ` ${res}` : res}`
					},
					fail: err => {
						console.log(err,'err')
						this.loading = false;
						uni.hideLoading()
					},
					closed: () => {
						this.loading = false;
					}
				})
			},
			// 开启socket
			openSocket(data) {
				uni.showLoading({
					title:'生成中...',
				})
				ioSocket({
					data,
					connect: () => {
						this.result = ''
					},
					success: data => {
						if(this.loading) {
							uni.hideLoading()
						}
						this.result += `${this.isEnOrNum(data) ? ` ${data}` : data}`
					},
					close: msg => {
						this.loading = false;
						console.log('close callback')
					},
					fail: err => {
						uni.hideLoading()
						this.loading = false;
						this.aiThinking = false
					},
					socketDistance: distance => {
						this.socketDistance = distance
					}
				})
			},
			isEnOrNum(str) {
				return str.match("[a-zA-Z0-9]+")   //判断英文和数字
			},
			// 初始化能力对象
			setVariables() {
				const arr = this.data.variables.split(';')
				const variables = arr.map(item => {
					const child = item.split('@')
					const [title,key,placeholder,voice] = child
					return {
						title,key,placeholder,voice,
						value: ''
					}
				})
				this.variables = variables
			},
			// 删除结果
			deleteResult() {
				uni.showModal({
					title:'确定要删除结果吗？',
					success:(res) => {
						if(res.confirm) {
							this.result = ''
						}
					}
				})
			},
			// 复制文案
			copy() {
				uni.setClipboardData({
					data: this.result,
					success: function () {
						uni.showToast({
							title: '复制成功！'
						})
					}
				});
			},
			recordingSuccess(text) {
				this.$set(this.talkingItem,'value',text)
			},
			// 长按启用麦克风说话
			startRecord(item) {
				uni.showLoading({
					title:'讲话中...'
				})
				this.talkingItem = item;
				// #ifdef H5
				this.$refs.recording.start()
				// #endif
				// #ifdef APP
				this.$refs.appRecording.start()
				// #endif
			},
			// 录音完毕
			stopRecord() {
				uni.hideLoading()
				// #ifdef H5
				this.$refs.recording.stop()
				// #endif
				// #ifdef APP
				this.$refs.appRecording.stop()
				// #endif
			},
		}
	}
</script>

<style lang="scss" scoped>
.createRoom {
	padding: 30rpx;
	.item {
		margin-top: 15rpx;
		background: rgba(42,43,61,0.6);
		box-shadow: 0 0 13rpx 0 rgba(0,0,0,0.51);
		border-radius: 20rpx;
		margin-bottom: 33rpx;
		position: relative;
		padding: 20rpx 0 30rpx;
		&.c {
			margin-top: 85rpx;
			padding-top: 60rpx;
		}
		.title {
			$h: 80rpx;
			border: 2rpx solid #58E789;
			box-shadow: 0px 15px 27px 0px rgba(0,0,0,0.25);
			border-radius: math.div($h,2);
			line-height: $h;
			text-align: center;
			padding: 0 50rpx;
			font-size: 28rpx;
			color: #FFFFFF;
			position: absolute;
			top: math.div(-$h,2);
			display: inline-block;
			background-color: #1A1D30;
			left: 25rpx;
		}
		.itemBody {
			padding: 0 30rpx;
			font-size: 28rpx;
			line-height: 1.8;
			color: #FFFFFF;
			white-space: pre-line;
			position: relative;
			.stop {
				position: absolute;
				width: 80rpx;
				right: 20rpx;
				$h: 40rpx;
				line-height: $h;
				height: $h;
				font-size: 24rpx;
				top: -40rpx;
				border-radius: math.div($h,2);
				background-color: $uni-bg-color-grey;
				color: #333;
				text-align: center;
			}
			&.placeholder {
				color: $uni-text-color-grey;
			}
			.textArea {
				width: 100%;
				font-size: 28rpx;
				line-height: 1.8;
				color: #FFFFFF;
				height: 170rpx;
			}
		}
		.textCount {
			text-align: right;
			font-size: 24rpx;
			color: rgba(255, 255, 255, 0.4);
			margin-top: 10rpx;
		}
		.handle {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			margin-top: 20rpx;
			.btn {
				width: 125rpx;
				height: 55rpx;
				background: #1A1D30;
				box-shadow: 0px 15rpx 27rpx 0px rgba(0,0,0,0.25);
				border-radius: 10rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-left: 12rpx;
				font-size: 25rpx;
				.icon {
					$s: 25rpx;
					width: $s;
					height: $s;
					margin-right: 8rpx;
				}
				.delete {
					width: 32rpx;
					height: 22rpx;
					margin-right: 8rpx;
				}
				&.plain {
					border: 2rpx solid #58E789;
					box-sizing: border-box;
					color: #58E789;
				}
				&.dark {
					color: #000002;
					background: linear-gradient(0deg, #32ECDF 0%, #57E78C 100%);
				}
			}
		}
	}
	.audioBtn {
		margin-left: auto;
		width: 262rpx;
		height: 76rpx;
		background: linear-gradient(0deg, #32ECE0 0%, #57E78B 100%);
		border-radius: 38rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #000002;
		font-size: 28rpx;
		.icon {
			width: 30rpx;
			height: 37rpx;
			margin-right: 10rpx;
		}
	}
	.create {
		$h: 76rpx;
		margin: 60rpx auto;
		font-size: 32rpx;
		text-align: center;
		line-height: $h;
		color: #000002;
		width: 672rpx;
		height: $h;
		background: linear-gradient(0deg, #32ECE0 0%, #57E78B 100%);
		border-radius: math.div($h,2);
	}
}
</style>
